import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Spin } from 'antd';
import { Upload, message, Modal } from 'antd';
import { connect, useDispatch } from 'umi';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import styles from './index.less';

const Page = () => {
  const [spinning, setSpinning] = useState(false);
  const [subLoading, setSubLoading] = useState(false);
  // 是否编辑
  const [isEdit, setIsEdit] = useState(false);
  // const [loading, setLoading] = useState(false);
  // logo
  const [imageUrl, setImageUrl] = useState('');
  const [isLogoUpdating, setIsLogoUpdating] = useState(false);
  const [logoId, setLogoId] = useState([]);
  // 背景墙图片
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [fileList, setFileList] = useState([]);
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const [isBgLogoUpdating, setIsBgLogoUpdating] = useState(false);

  useEffect(() => {
    initData();
    return () => {};
  }, []);

  useEffect(() => {
    form.setFieldsValue({
      carouselIdList: fileList?.map((f) => f.uid),
    });
    return () => {};
  }, [fileList]);

  const onFinish = (formData) => {
    const { carouselList, logo, ...values } = formData;
    setSubLoading(true);
    dispatch({
      type: 'settingsModel/updateCarousel',
      payload: { ...values },
    }).then((res) => {
      setSubLoading(false);
      if (res.code === 0) {
        message.success('操作成功');
        initData();
        setIsEdit(false);
      } else {
        message.error(res.message);
      }
    });
  };

  const initData = () => {
    setSpinning(true);
    dispatch({
      type: 'settingsModel/getFormData',
    })
      .then((res) => {
        setSpinning(false);
        if (res && res.code === 0) {
          setImageUrl(
            res.data?.logoBase64
              ? URL.createObjectURL(
                  imageBase64ToBlob(
                    res.data?.logoBase64,
                    res.data?.logoSuffix?.replace('.', 'image/'),
                  ),
                )
              : '',
          );
          setFileList(
            res.data?.carouselList.map((e) => ({
              name: e.fileName,
              uid: e.id,
              url: URL.createObjectURL(
                imageBase64ToBlob(e.fileBase64, e.fileSuffix.replace('.', 'image/')),
              ),
            })),
          );
          form.setFieldsValue({
            sloganCn: res.data?.sloganCn,
            sloganEn: res.data?.sloganEn,
            logoId: res.data?.logoId,
            id: res.data?.id,
          });
          setLogoId(res?.data?.logoId);
        } else {
          message.error(res?.message);
        }
      })
      .catch(() => setSpinning(false));
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const imageBase64ToBlob = (urlData, type = 'image/jpeg') => {
    try {
      const mime = type;
      // 去掉url的头，并转化为byte
      const bytes = window.atob(urlData);
      // 处理异常,将ascii码小于0的转换为大于0
      const ab = new ArrayBuffer(bytes.length);
      // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
      const ia = new Uint8Array(ab);

      for (let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }

      return new Blob([ab], {
        type: mime,
      });
    } catch (e) {
      const ab = new ArrayBuffer(0);
      return new Blob([ab], {
        type: type,
      });
    }
  };

  // logo上传按钮
  const uploadButton = (
    <div>
      <LoadingOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );
  // 背景墙上传按钮
  const bgUploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );

  // 获取base64
  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };
  // logo上传事件
  const beforeUpload = (file) => {
    const suf = file.name.split('.').pop().toLowerCase();
    const isJpgOrPng = suf === 'jpg' || suf === 'jpeg' || suf === 'png';
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!(isJpgOrPng && isLt2M && !isLogoUpdating)) {
      if (isLogoUpdating) {
        message.warning('正在上传logo图片');
        return false;
      }
      if (!isJpgOrPng) {
        message.error('请上传jpg/jpeg/png格式的图片');
        return false;
      }
      if (!isLt2M) {
        message.error('图片大小不能超过5M');
        return false;
      }
      form.setFieldsValue({ logoId });
      return false;
    }
    // return isJpgOrPng && isLt2M;
    uploadLogoFile(file);
    return false;
  };
  // logo变更事件
  const uploadLogoFile = (file) => {
    // setLoading(true);
    setIsLogoUpdating(true);
    const params = new FormData();
    params.append('fileName', file.name.substring(0, file.name.lastIndexOf('.')));
    params.append('fileSuffix', `.${file.type?.split('/')[1]}`);
    params.append('file', file);
    params.append('fileType', 1);
    dispatch({
      type: 'settingsModel/uploadImageFile',
      payload: params,
    }).then((res) => {
      if (res.code === 0) {
        form.setFieldsValue({ logoId: res.data });
        setLogoId(res.data);
        // Get this url from response in real world.
        getBase64(file, (imageUrl) => {
          // setLoading(false);
          setImageUrl(imageUrl);
          setIsLogoUpdating(false);
        });
      } else {
        message.error(res.message);
        setIsLogoUpdating(false);
      }
    });
  };

  // 背景墙事件
  const bghandleCancel = () => setPreviewVisible(false);

  const bghandlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await bggetBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewVisible(true);
    setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
  };
  // 背景墙事件
  const bggetBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  };
  const beforeBgUpload = (file) => {
    const suf = file.name.split('.').pop().toLowerCase();
    const isJpgOrPng = suf === 'jpg' || suf === 'jpeg' || suf === 'png';

    const isLt2M = file.size / 1024 / 1024 < 5;

    if (!(isJpgOrPng && isLt2M && !isBgLogoUpdating)) {
      if (isBgLogoUpdating) {
        message.warning('正在上传背景图片');
        return false;
      }
      if (!isJpgOrPng) {
        message.error('请上传jpg/jpeg/png格式的图片');
        return false;
      }
      if (!isLt2M) {
        message.error('图片大小不能超过5M');
        return false;
      }
      // form.setFieldsValue({ carouselIdList: fileList.map((f) => f.uid) });
      return false;
    }
    return isJpgOrPng && isLt2M;
  };
  // 背景墙事件
  const bghandleChange = ({ file, fileList }) => {
    // 图片上传至在before处return false后仍然会出发change，需要在此处理一下回显
    if (!file?.status || file?.status === 'removed') {
      const tempArr = fileList.filter((f) => f.uid !== file.uid);
      // form.setFieldsValue({
      //   carouselIdList: tempArr.map((f) => f.uid),
      // });
      setFileList(tempArr);
      return;
    }
    setFileList(fileList);
  };
  const handleBgFile = ({ file }) => {
    setIsBgLogoUpdating(true);
    const params = new FormData();
    params.append('fileName', file.name.substring(0, file.name.lastIndexOf('.')));
    params.append('fileSuffix', `.${file.type?.split('/')[1]}`);
    params.append('file', file);
    params.append('fileType', 2);
    dispatch({
      type: 'settingsModel/uploadImageFile',
      payload: params,
    })
      .then((res) => {
        if (res.code === 0) {
          setTimeout(() => {
            let tempArr = [];
            if (fileList.find((f) => f.uid === file.uid)) {
              tempArr = fileList.map((f) => {
                if (f.uid === file.uid) {
                  return { ...f, uid: res.data, status: 'done' };
                }
                return f;
              });
            } else {
              // file['uid'] = res.data;
              // file['status'] = 'done';
              // console.log(file);
              tempArr = fileList.concat([
                {
                  url: URL.createObjectURL(file),
                  uid: res.data,
                  name: file.name,
                },
              ]);
            }
            // form.setFieldsValue({
            //   carouselIdList: tempArr.map((f) => f.uid),
            // });
            setFileList(tempArr);
            setIsBgLogoUpdating(false);
          }, 500);
        } else {
          message.error(res?.message);
          const tempArr = fileList.filter((f) => f.uid !== file.uid);
          setFileList(tempArr);
          setIsBgLogoUpdating(false);
        }
      })
      .catch((e) => {
        console.log(e);
        message.error('上传失败');
        const tempArr = fileList.filter((f) => f.uid !== file.uid);
        setFileList(tempArr);
      });
  };

  return (
    <div className={styles.root}>
      <Spin spinning={spinning}>
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="id"
            name="id"
            hidden
            rules={[{ required: true, message: '请输入展示文字' }]}
          >
            <Input disabled={!isEdit} />
          </Form.Item>

          <Form.Item
            label="展示文字"
            name="sloganCn"
            rules={[
              { required: true, message: '请输入展示文字' },
              { max: 80, message: '请输入80位以内展示文字' },
              { pattern: /^[\u4e00-\u9fa5]|[a-zA-Z]*$/, message: '请输入中英文' },
            ]}
          >
            <Input disabled={!isEdit} />
          </Form.Item>

          <Form.Item
            label="英文翻译"
            name="sloganEn"
            rules={[
              { max: 200, message: '请输入200位以内英文翻译' },
              { pattern: /^([a-zA-Z]|\s)*$/, message: '请输入英文字符' },
            ]}
          >
            <Input disabled={!isEdit} />
          </Form.Item>

          {/* <Form.Item
            label=""
            name="logoId"
            hidden
          ></Form.Item>

          <Form.Item
            label=""
            name="carouselIdList"
            hidden
          ></Form.Item> */}

          <Form.Item
            label="展示logo"
            name="logoId"
            valuePropName="logoId"
            getValueFromEvent={() => {}}
            rules={[
              { required: true, message: '' },
              ({ getFieldValue }) => ({
                validator() {
                  if (getFieldValue('logoId')) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('请选择展示logo'));
                },
              }),
            ]}
          >
            <Upload
              name="logoUrl"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              beforeUpload={beforeUpload}
              // onChange={handleChange}
              disabled={!isEdit}
            >
              {imageUrl && !isLogoUpdating ? (
                <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>

          <Form.Item
            label="背景轮播图"
            name="carouselIdList"
            valuePropName="carouselIdList"
            getValueFromEvent={() => {}}
            rules={[
              { required: true, message: '' },
              ({ getFieldValue }) => ({
                validator() {
                  if (
                    getFieldValue('carouselIdList') &&
                    getFieldValue('carouselIdList')?.length > 0
                  ) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('请选择背景轮播图'));
                },
              }),
            ]}
          >
            <>
              <Upload
                listType="picture-card"
                fileList={fileList}
                onPreview={bghandlePreview}
                onChange={bghandleChange}
                customRequest={handleBgFile}
                beforeUpload={beforeBgUpload}
                disabled={!isEdit}
              >
                {fileList.length >= 5 || !isEdit ? null : bgUploadButton}
              </Upload>
              <Modal visible={previewVisible} title={<>&nbsp;</>} footer={null} onCancel={bghandleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
            {!isEdit ? (
              <Button type="primary" onClick={() => setIsEdit(true)}>
                编辑
              </Button>
            ) : (
              <Button type="primary" onClick={() => form.submit()} loading={subLoading}>
                保存
              </Button>
            )}
          </Form.Item>
        </Form>
      </Spin>
    </div>
  );
};

export default connect((state) => state)(Page);
